<?php

function main_handler($event, $context) {
//    echo system("mkdir -p /tmp");
//    echo system("mkdir -p /tmp/log");
//    echo system("mkdir -p /tmp/cache");
//    echo system("mkdir -p /tmp/tp5Car");
//    echo system("chmod -R 755 /tmp/");

//    echo "-------  入口执行时间：" . date("Y-m-d H:i:s") . "  --------- \r\n";
    $_SERVER = [];
    $_SERVER["IS_SCF"] = true;
    $_SERVER["DOCUMENT_ROOT"] = __DIR__;
    if(isset($event->Type) && $event->Type == "Timer"){ // 定时任务触发器
        echo "=========".var_export($event, true)."============";
        $path = "web/cron/{$event->TriggerName}"; // 路由
        $_SERVER["TIMER_TRIGGER"] = 1;
        $result = handelSystem($path, [], [], [], [], false);
        return array(
            'isBase64Encoded' => false,
            'statusCode' => 200,
            'headers' => array('Content-Type' => 'application/json;charset=utf-8', "Access-Control-Allow-Origin" => "*", 'Cache-Control' => "max-age=10"),
            'body' => json_encode($result, JSON_UNESCAPED_UNICODE) //转义中文
        );
    }else { // API网关
        if($event->requestContext->path == "/"){ // 自定义域名
            $path = substr($event->path, strlen($event->requestContext->path));
            $_SERVER["HTTP_HOST"] = $event->headers->host; //加上域名
        }else{
            $path = substr($event->path, strlen($event->requestContext->path . "/"));
            $_SERVER["HTTP_HOST"] = $event->headers->host . "/" . $event->requestContext->stage . $event->requestContext->path; // 加上域名
        }
        $_SERVER["REMOTE_ADDR"] = $event->requestContext->sourceIp;   // ip地址，不传支付会报错
        $_SERVER["REQUEST_METHOD"] = $event->httpMethod; // http请求类型
        $_SERVER["HTTPS"] = 1;   // 改成https
        $path = ltrim($path, "/");
        if(empty($path)){
            $path = "index.html";
        }else if($path == "saas" || $path == "saas/"){
            $path = "saas/index.html";
        }
        // 处理html, js, css文件
        if (preg_match('#\.html.*|\.js.*|\.css.*|\.html.*#', $path)) {
            return handelResource($path);
        }
        if (
            preg_match('#\.gif.*|\.jpg.*|\.png.*|\.jepg.*|\.bmp.*|\.ico.*#', $path) || // 处理图片
            preg_match('/(\.swf|\.mp4|\.mp3|\.acc)/i', $path) // 视频文件、音乐文件
        ) {
            return handelResource($path, true);
        }

        $header = $queryString = array();
        $event->headers = (array)$event->headers;
        foreach ($event->headers as $k => $v) {
            $header[$k] = "{$k}: {$v}";
        }
        $requestParam = ["param" => [], "files" => []];
        if (!empty($event->body)) {
            $requestParam = handelBodyData($event);
        }
        if (!empty($event->queryString)) {
            foreach ($event->queryString as $k => $v) {
                $queryString[$k] = $v;
            }
        }
        $result = handelSystem($path, $header, $requestParam["param"], $requestParam["files"], $queryString);
        //集成响应结果
        if (isset($result["returnFile"])) { //下载文件的标识key
            return array(
                "isBase64Encoded" => true,
                "statusCode" => 200,
                "headers" => $result["returnFile"]["header"],
                "body" => base64_encode($result["returnFile"]["content"]),
            );
        } elseif(isset($result["returnResource"])) { // 返回静态资源，如图片
            return array(
                "isBase64Encoded" => true,
                "statusCode" => 200,
                'headers' => ['Content-Type' => '', 'Cache-Control' => "max-age=10", 'Accept-Ranges' => 'bytes'],
                "body" => base64_encode($result["returnResource"]),
            );
        } else {
            if(is_string($result)){ // 输出html
                return array(
                    'isBase64Encoded' => false,
                    'statusCode' => 200,
                    'headers' => array('Content-Type' => 'text/html;charset=utf-8', "Access-Control-Allow-Origin" => "*", 'Cache-Control' => "max-age=10"),
                    'body' => $result
                );
            }else { // 数据json数据
                return array(
                    'isBase64Encoded' => false,
                    'statusCode' => 200,
                    'headers' => array('Content-Type' => 'application/json;charset=utf-8', "Access-Control-Allow-Origin" => "*", 'Cache-Control' => "max-age=10"),
                    'body' => json_encode($result, JSON_UNESCAPED_UNICODE) //转义中文
                );
            }
        }
    }
}

function handelSystem($path, $header, $requestParam, $files, $queryString, $recordLog = false){
    $_SERVER['SCRIPT_FILENAME'] = $_SERVER['argv'][0] = __DIR__ . "/index.php"; //为了能正常解析框架根目录，加载vendor扩展
    try {
        require_once __DIR__ . '/thinkphp/base.php';
        if (!defined('__PUBLIC__')) {
            define('__PUBLIC__', '/'); // 因为静态资源已经指定了public了，所以默认/
        }

        $app = \think\Container::get('app', true); //云开发里必须创建新实例，否则会拿到上次的实例对象
        $app->path(__DIR__ . "/application/");

        if ($recordLog) {
            // 指定日志类驱动
            \think\Loader::addClassMap([
                'think\\log\\driver\\File' => __DIR__ . '/File.php', // 日志存储在腾讯云cos里，要收费，必要时候才存到桶里
            ]);
        }

        if (is_file(__DIR__ . "/wsConfig.json")) {
            $wsConfig = json_decode(file_get_contents(__DIR__ . '/wsConfig.json'), true);
            $app->env->set(isset($wsConfig["system"]) ? $wsConfig["system"] : []);
            unset($wsConfig);
        }

        $app->initialize();

        // 请求头
        if (!empty($header)) {
            $app->request->withHeader($header);
        }
        if (!empty($files)) { //上传文件、图片处理
            $temp_file = tempnam(sys_get_temp_dir(), "php"); // 生成临时文件
            file_put_contents($temp_file, base64_decode($files["content"])); // 把文件流写入临时文件
            $_FILES["file"] = ["name" => $files["name"], "type" => $files["type"], "tmp_name" => $temp_file, "error" => 0, "size" => $files["size"]];
        }
        // POST请求
        if (!empty($requestParam)) {
            $app->request->withPost($requestParam);
        }
        // GET请求
        if (!empty($queryString)) {
            $app->request->withGet($queryString);
        }
        $app->request->setPathinfo($path); //请求路由

        $response = $app->run();
        $result = $response->getData();
    }catch (Exception $e){
        $result = \app\common\util\ErrorCode::code("try_error", $e->getMessage());
        $result["file"] = $e->getFile();
        $result["line"] = $e->getLine();
        if (false !== stripos($result["msg"], 'Error while sending')) {
            $result = handelSystem($path, $header, $requestParam, $files, $queryString);
        }else{
            \app\common\util\Tools::writeLog(var_export($result, true).$e->getTraceAsString(),  "index_exception.txt");
        }
    }
    return $result;
}

function handelBodyData($event){
    $formDataTag = "multipart/form-data; boundary=";
    $requestParam = ["param" => [], "files" => []];
    if (strpos($event->headers["content-type"], $formDataTag) !== false) { //form-data头数据
        $key = "--" . str_replace($formDataTag, "", $event->headers["content-type"]);
        $params = preg_split("/[\\s]*${key}-*[\\s]*/", $event->body);
        array_pop($params);
        array_shift($params);
        foreach ($params as $str) {
            $strArr = explode("\r\n\r\n", $str);
            if (count($strArr) < 2) {
                $strArr = explode("\n\n", $str);
            }
            $string = preg_replace("/[\\s\\S]*Content-Disposition: form-data; name=\"([^\"]+)\"[\\s\\S]*/", "$1", $strArr);
            if ($string[0] === 'file') { // 文件类型
                $requestParam["files"] = isset($string[1]) ? json_decode($string[1], true) : "";
            } else {
                $requestParam["param"][$string[0]] = isset($string[1]) ? $string[1] : "";
            }
        }
    } else if (strpos($event->headers["content-type"], "xml") !== false) { // xml数据头 ,目前微信支付回调返回xml数据
        $requestParam["param"] = ["xml" => $event->body];
    } else {
        if (is_string($event->body)) {
            if (!($requestParam["param"] = json_decode($event->body, true))) {
                parse_str($event->body, $requestParam["param"]);
            }
        } else if (is_array($event->body)) {
            $requestParam["param"] = $event->body;
        } else {
            foreach ($event->body as $k => $v) {
                $requestParam["param"][$k] = $v;
            }
        }
    }
    return $requestParam;
}

// 处理静态资源
function handelResource($path, $isBase64 = false){
    $filename = "/var/user/public/" . $path; // 所有静态资源都指定到public目录下
    try {
        $handle = fopen($filename, "r");
        $contents = fread($handle, filesize($filename));
        fclose($handle);
    }catch (Exception $e){
        $contents = file_get_contents($filename);
    }
    return array(
        'isBase64Encoded' => $isBase64,
        'statusCode' => 200,
        'headers' => ['Content-Type' => '', 'Cache-Control' => "max-age=10", 'Accept-Ranges' => 'bytes'],
        'body' => $isBase64 ? base64_encode($contents) : $contents
    );
}
?>